package com.hq.cms.web.controllers;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.hq.cms.core.CMSRuntimeException;
import com.hq.cms.domain.User;
import com.hq.cms.service.UserInfoService;
import com.hq.cms.web.Constant;
import com.hq.cms.web.forms.UserForm;

@Controller
public class UserInfoController {
	@Resource
	private UserInfoService userInfoService;
	
	
	//  路径    reg 并且是get提交 就会方法此方法
	@RequestMapping(value="reg",method=RequestMethod.GET)
	// a标签跳转 默认都是get提交
	public String toreg(Model model) {
		// 模型  绑定 因为要用的springForm 标签
		model.addAttribute("userForm", new UserForm());
		// 因为springMVC.xml已经设置好前缀了 所以 我们需要指定跳转路径的位置
		return "passport/reg";
	}


	@RequestMapping(value="login",method=RequestMethod.GET)
	public String tologin(Model model) {
		model.addAttribute("userForm", new UserForm());
		return "passport/login";
	}
	
	// 执行注册操作
	@RequestMapping(value="reg",method=RequestMethod.POST)
	public String doReg(UserForm userForm,Model model) {
		try {
			int i=userInfoService.reg(userForm);
		} catch (CMSRuntimeException e) {
			model.addAttribute("message", e.getMessage());
			return "passport/reg";
		}
		return "redirect:login";
	}
	
	//执行登录的操作
	@RequestMapping(value="login",method=RequestMethod.POST)
	public  String  login(UserForm userForm,Model model,HttpServletRequest request) {
		try {
			//参数是UserForm 但是 返回值 是user
			User user=userInfoService.log(userForm);
			// 如果登录成功需要把user对象  放入到 作用域之中
			//request.getSession().setAttribute("_LOGIN_USER_", user);
			Constant.setLoginUser(request, user);

		} catch (CMSRuntimeException e) {
			model.addAttribute("message", e.getMessage());
			return "passport/login";
		}
		return "redirect:index";
	}
	
	
	// 退出的功能  跳转到 初始页面 同时 注销session***
	@RequestMapping("logout")
	public String logout(HttpServletRequest reuqest) {
		//  注销session
		reuqest.getSession().invalidate();
		return "redirect:login";
	}
	
}
